import Vue from 'vue'
import VueRouter from 'vue-router'
// 引入状态管理
import store from '../vuex/store';
//组件按需加载
const Login = () => import('@/views/login')
const Index = () => import('@/views/index')
const BatchList = () => import('@/views/batch/batchList')
const DataList = () => import('@/views/data/dataList')
Vue.use(VueRouter)


// redirect 重定向
// 在父子嵌套结构中，父级的redirect指向子级children里的path

// meta 元数据
// 可以作用判断用户是否已登陆
// 可以通过meta值，展示面包屑

// hidden 是否需要展示该路由是否渲染该路由入口
const routes = [
  {
    path: '/',
    name: 'Login',
    hidden: true,
    component: Login,
    meta: {
      requireAuth: false
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    hidden: true,
    meta: {
      requireAuth: false
    }
  },
  {
    path: '/index',
    name: 'Index',
    component: Index,
    iconCls: 'el-icon-tickets',
    meta: {
      requireAuth: true
    },
    redirect:'/index/batchList',
    children: [
      {
        path: '/index/batchList',
        name: 'BatchList',
        component: BatchList,
        meta: {
          requireAuth: true
        }
      },
      {
        path: '/index/dataList',
        name: 'DataList',
        component: DataList,
        meta: {
          requireAuth: true
        }
      }, 
    ]
  },
  {path: '*', redirect: '/', hidden: true}
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//全局路由守卫
router.beforeEach((to, from, next) => {
  if (to.path == '/' || to.path == "/login" || to.path == 'spot') {
    next()
  } else {
    //获取用户登录成功后储存的登录标志
    let userdata = localStorage.getItem("userdata");
    //如果登录标志存在，即用户已登录
    if (userdata) {
      //设置vuex登录状态为已登录
      store.state.user = true;
      next();
      //如果已登录，还想想进入登录注册界面，则定向回首页
      if (!to.meta.requireAuth) {
        next({
          path: '/'
        })
      }
    }
    //如果登录标志不存在，即未登录
    else {
      //用户想进入需要登录的页面，则定向回登录界面
      if (to.meta.requireAuth) {
        next({
          path: '/',
        })

      }
      //用户进入无需登录的界面，则跳转继续
      else {
        next()
      }
    }
  }
})

export default router
